package com.app.mvc.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;

import com.app.mvc.ultil.HibernateUtil;

public abstract class AbstractHibernateDaoSupport<C, ID extends Serializable>
		implements Dao<C, ID> {
	private Class<C> classPersistent;

	protected AbstractHibernateDaoSupport(Class<C> classPersistent) {
		this.classPersistent = classPersistent;
	}

	public Class<C> getClassPersistent() {
		return classPersistent;
	}

	public Session getSession() {
		return HibernateUtil.getSession();
	}

	/**
	 * find by criteria
	 */
	@SuppressWarnings("unchecked")
	protected final List<C> findByCriteria(Criterion... criterion) {
		Criteria crit = getSession().createCriteria(getClassPersistent());
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return crit.list();
	}

	/**
	 * find all object
	 */
	public List<C> findAll() {
		return findByCriteria();
	}

	/**
	 * find by id
	 */
	@SuppressWarnings("unchecked")
	public C findById(ID id) {
		C entity = null;
		try {
			entity = (C) getSession().get(getClassPersistent(), id);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return entity;
	}
	
	

}
